package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取登录页面传来的用户名和密码
        String username = request.getParameter("username");
        String password=request.getParameter("password");
        String remember = request.getParameter("remember");

        UserService service = new UserService();
        User user = service.login(username, password);
        if (user!=null){
            //登陆成功，判断remember是否被选中
            if ("1".equals(remember)){
                //remember被选中，将用户名和密码放到cookie中去，存放一周
                //获取cookie对象
                Cookie ck_username = new Cookie("username",username);
                Cookie ck_password = new Cookie("password", password);
                //设置cookie存活时间
                ck_password.setMaxAge(7*24*60*60);
                ck_username.setMaxAge(7*24*60*60);

                //将cookie放到response中
                response.addCookie(ck_username);
                response.addCookie(ck_password);

            }

            //登录成功,重定位到brand.jsp页面，使用重定向，页面跳转，而且没有数据共享
            //在页面上显示对应的用户名，动态web，随意brand要使用jsp页面
            //使用session实现一个会话不同请求间的数据共享
            //获取session对象
            HttpSession session = request.getSession();
            //将user对象放在session域中
            session.setAttribute("user",user);
            //这里要加上虚拟路径，重定位是浏览器发出
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/SelectAllServlet");
        }else {
            //登录失败，跳转到登录页面，给出错误提示信息
            //在服务器内，使用请求转发
            request.setAttribute("errorMSG","用户名或密码不正确");

            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}